<template>
  <w-dialog :border="false" closeFree width="60vw" @ok="selectOk" :title="title" v-model="visible">
    <div class="picker">
      <div class="candidate" v-loading="loading">
        <el-form
          :model="queryParams"
          ref="queryForm"
          v-show="showSearch"
          :inline="true"
          @submit.prevent
        >
          <el-form-item label="角色名称" prop="roleNameLike">
            <el-input
              v-model="queryParams.roleNameLike"
              placeholder="请输入角色名称"
              clearable
              size="default"
              style="width: 230px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <search-button @click="handleQuery" />
            <reset-button @click="resetQuery" />
          </el-form-item>
        </el-form>

        <el-table
          :row-key="getRowKey"
          ref="multipleTable"
          v-loading="loading"
          :data="roleList"
          @selection-change="handleSelectionChange"
          @row-click="handleCurrent"
        >
          <el-table-column
            v-if="!isRadio"
            type="selection"
            width="55"
            align="center"
            reserve-selection
          />
          <el-table-column label="角色名称" prop="roleName" :show-overflow-tooltip="true" />
          <el-table-column label="角色类型" prop="roleType" align="center" min-width="100">
            <template #default="scope">
              <el-tooltip
                v-if="scope.row.roleType === '0'"
                content="【系统内置】授权后可拥有所有菜单所有按钮权限"
                placement="right-start"
                effect="light"
              >
                <el-tag type="danger">超级角色</el-tag>
              </el-tooltip>
              <el-tooltip
                v-else-if="scope.row.roleType === '1'"
                placement="right-start"
                effect="light"
              >
                <template #content>
                  <div
                  >【系统内置】只有配置类型角色授权后才可以做系统的配置管理<br />配置管理包括角色、菜单、字典、参数和ZCache等管理权限</div
                  >
                </template>
                <el-tag type="warning">配置角色</el-tag>
              </el-tooltip>
              <el-tooltip
                v-else-if="scope.row.roleType === '2'"
                placement="right-start"
                effect="light"
              >
                <template #content>
                  <div
                  >用于实际业务系统的功能应用操作<br />即使进行菜单按钮授权也无法操作以上配置管理功能</div
                  >
                </template>
                <el-tag type="success" effect="light">应用角色</el-tag>
              </el-tooltip>
              <el-tag v-else>{{ scope.row.roleType }}</el-tag>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-show="total > 0"
          small
          layout="prev, pager, next"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </div>
      <div class="selected">
        <div class="count">
          <span>已选 {{ select.length }} 项</span>
          <span @click="clearSelected">清空</span>
        </div>
        <div class="org-items" style="height: 350px">
          <el-empty
            :image-size="100"
            description="请点击左侧列表选择数据"
            v-show="select.length === 0"
          />
          <div v-for="(org, index) in select" :key="index" class="org-item">
            <div>
              <i class="iconfont icon-bumen"></i>
              <span class="name">{{ org.roleName }}</span>
            </div>
            <el-icon class="el-icon el-icon-close" @click="noSelected(org, index)"
            ><Close
            /></el-icon>
            <!-- <i class="el-icon-close" @click="noSelected(org,index)"></i> -->
          </div>
        </div>
      </div>
    </div>
  </w-dialog>
</template>

<script>
import { listRole } from './rolePicker.js'

export default {
  name: 'OrgPicker',
  components: {},
  props: {
    title: {
      default: '请选择',
      type: String
    },
    type: {
      default: 'org', //org选择部门/人员  user-选人  dept-选部门 role-选角色
      type: String
    },
    isRadio: {
      default: false,
      type: Boolean
    },
    // multiple: {
    //   //是否多选
    //   default: false,
    //   type: Boolean,
    // },
    selected: {
      default: () => {
        return []
      },
      type: Array
    }
  },
  emits: ['ok'],
  data() {
    return {
      visible: false,
      loading: false,
      checkAll: false,
      searchUsers: [],
      nodes: [],
      select: [],
      search: '',
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        delFlag: 'N',
        orderBy: 'ROLE_SORT',
        roleNameLike: undefined,
        roleKeyLike: undefined,
        status: undefined
      },
      // 表单参数
      form: {}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getRowKey(row) {
      return row.roleId
    },
    /** 查询角色列表 */
    getList() {
      this.loading = true
      listRole(
        this.addDateRange(this.queryParams, ['createTimeStart', 'createTimeEnd'], this.dateRange)
      ).then((response) => {
        this.roleList = response.data.list
        this.total = response.data.total
        this.loading = false
      })
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.queryParams.pageSize = 10
      this.getList()
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([])
      }
      this.form = {
        roleId: undefined,
        roleName: undefined,
        roleKey: undefined,
        roleSort: 0,
        status: 'Y',
        menuIds: [],
        scopes: [],
        remark: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      if (!this.isRadio) {
        this.select = selection
        this.ids = selection.map((item) => item.roleId)
        this.single = selection.length != 1
        this.multiple = !selection.length
      }
    },
    handleCurrent(row) {
      //row就是行信息
      if (this.isRadio) {
        this.select = [row]
        this.ids = row.roleId
        // this.$refs.multipleTable.toggleRowSelection(row) // 传入行信息，使得该行复选框打上勾
      }
    },

    show() {
      this.getOrgList()
      this.visible = true
      this.init()
    },
    getOrgList() {
      this.loading = true
      listRole({ orderBy: 'ROLE_SORT', pageNum: 1, pageSize: 10, delFlag: 'N' }).then(
        (response) => {
          this.loading = false
          this.nodes = response.data.list
        }
      )
    },
    selectToLeft() {
      let nodes = this.search.trim() === '' ? this.nodes : this.searchUsers
      nodes.forEach((node) => {
        for (let i = 0; i < this.select.length; i++) {
          if (this.select[i].id === node.id) {
            node.selected = true
            break
          } else {
            node.selected = false
          }
        }
      })
    },
    noSelected(org, index) {
      console.log(222)
      this.select.forEach((item) => {
        if (item.roleId == org.roleId) {
          this.$refs.multipleTable.toggleRowSelection(item, false)
        }
      })
      this.select.splice(index, 1)
    },
    recover() {
      this.select.forEach((item) => {
        this.$refs.multipleTable.toggleRowSelection(item, false)
      })
      this.select = []
    },
    selectOk() {
      this.$emit(
        'ok',
        Object.assign(
          [],
          this.select.map((v) => {
            v.avatar = undefined
            return v
          })
        )
      )
      this.visible = false
      this.recover()
    },
    clearSelected() {
      this.$confirm('您确定要清空已选中的项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.recover()
      })
    },
    close() {
      this.$emit('close')
      this.recover()
    },
    init() {
      this.checkAll = false
      this.nodes = []
      this.select = Object.assign([], this.selected)
      this.selectToLeft()
      setTimeout(() => {
        this.select.forEach((ite) => {
          this.roleList.forEach((item) => {
            if (item.roleId == ite.roleId) {
              this.$refs.multipleTable.toggleRowSelection(item, true)
            }
          })
        })
      }, 500)
    }
  }
}
</script>

<style lang="less" scoped>
.candidate,
.selected {
  position: absolute;
  display: inline-block;
  height: 400px;
  border: 1px solid #e8e8e8;
}

.picker {
  height: 402px;
  position: relative;
  text-align: left;
  .candidate {
    left: 0;
    top: 0;
    width: 55%;
    .role-header {
      padding: 10px !important;
      margin-bottom: 5px;
      border-bottom: 1px solid #e8e8e8;
    }

    & > div:first-child {
      padding: 5px 10px;
    }
  }

  .selected {
    right: 0;
    top: 0;
    width: 45%;
  }

  .org-items {
    overflow-y: auto;
    height: 310px;

    .el-icon-close {
      position: absolute;
      right: 5px;
      cursor: pointer;
      font-size: larger;
    }

    :deep(.org-item) {
      margin: 0 5px;
      border-radius: 5px;
      padding: 10px 5px;
      display: flex;
      .el-checkbox {
        margin-right: 10px;
      }

      .name {
        margin-left: 5px;
      }

      &:hover {
        background: #f1f1f1;
      }
    }
  }
}

.selected {
  border-left: none;

  .count {
    width: 100%;
    padding: 10px;
    display: inline-block;
    border-bottom: 1px solid #e8e8e8;
    margin-bottom: 5px;
    & > span:nth-child(2) {
      float: right;
      color: #c75450;
      cursor: pointer;
    }
  }
}

:deep(.el-dialog__body) {
  padding: 10px 20px;
}

.disabled {
  cursor: not-allowed !important;
  color: #8c8c8c !important;
}

::-webkit-scrollbar {
  float: right;
  width: 4px;
  height: 4px;
  background-color: white;
}

::-webkit-scrollbar-thumb {
  border-radius: 16px;
  background-color: #efefef;
}

:deep(.el-table) {
  height: calc(400px - 100px);
}
:deep(.el-table__body-wrapper) {
  height: calc(100% - 50px);
  overflow-y: auto;
  overflow-x: hidden;
}
:deep(.el-pagination) {
  float: right;
}
</style>
